<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-title">拼刀刀商城管理系统</div>

      <el-tabs v-model="activeTab" class="login-tabs">
        <el-tab-pane label="用户登录" name="user">
          <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="0" class="login-form">
            <el-form-item prop="username">
              <el-input v-model="userForm.username" placeholder="用户名" prefix-icon="el-icon-user" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="userForm.password" placeholder="密码" prefix-icon="el-icon-lock" type="password" show-password />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" :loading="loading" @click="handleUserLogin" class="login-button">登录</el-button>
            </el-form-item>
            <div class="login-options">
              <span class="register-link" @click="goToRegister">注册账号</span>
            </div>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="商家登录" name="merchant">
          <el-form :model="merchantForm" :rules="rules" ref="merchantFormRef" label-width="0" class="login-form">
            <el-form-item prop="username">
              <el-input v-model="merchantForm.username" placeholder="商家用户名" prefix-icon="el-icon-user" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="merchantForm.password" placeholder="密码" prefix-icon="el-icon-lock" type="password" show-password />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" :loading="loading" @click="handleMerchantLogin" class="login-button">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useUserStore } from '@/store/user'
import { useMerchantStore } from '@/store/merchant'
// import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { useRouter } from 'vue-router'

// 表单引用
const userFormRef = ref<FormInstance>()
const merchantFormRef = ref<FormInstance>()

// 激活的标签页
const activeTab = ref('user')

// 加载状态
const loading = ref(false)

// 用户表单数据
const userForm = reactive({
  username: localStorage.getItem('userUsername') || '',
  password: ''
})

// 商家表单数据
const merchantForm = reactive({
  username: localStorage.getItem('merchantUsername') || '',
  password: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 获取store和router
const userStore = useUserStore()
const merchantStore = useMerchantStore()
const router = useRouter()

// 强制跳转到指定页面的函数
const forceNavigate = async (path: string) => {
  console.log('强制跳转到:', path)
  try {
    await nextTick()
    await router.push(path)
    console.log('强制跳转完成')
  } catch (error) {
    console.error('强制跳转失败:', error)
  }
}

// 用户登录
const handleUserLogin = async () => {
  if (!userFormRef.value) return

  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        console.log('开始用户登录流程')
        const result = await userStore.login(userForm)
        console.log('用户登录结果:', result)
        if (result) {
          // 登录成功，保存用户名以便下次自动填充
          localStorage.setItem('userUsername', userForm.username)
          console.log('用户登录成功，应该已跳转到产品页面')
          // 使用强制跳转函数确保跳转
          await forceNavigate('/user/products')
        } else {
          console.log('用户登录失败')
        }
        // 登录失败的错误消息已经在响应拦截器中处理
      } catch (error) {
        console.error('登录出错:', error)
        // 错误消息已经在响应拦截器中处理
      } finally {
        loading.value = false
      }
    } else {
      console.log('表单验证失败')
    }
  })
}

// 商家登录
const handleMerchantLogin = async () => {
  if (!merchantFormRef.value) return

  await merchantFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        console.log('开始商家登录流程')
        const result = await merchantStore.login(merchantForm)
        console.log('商家登录结果:', result)
        if (result) {
          // 登录成功，保存商家用户名以便下次自动填充
          localStorage.setItem('merchantUsername', merchantForm.username)
          console.log('商家登录成功，应该已跳转到商家产品页面')
          // 使用强制跳转函数确保跳转
          await forceNavigate('/merchant/products')
        } else {
          console.log('商家登录失败')
        }
        // 登录失败的错误消息已经在响应拦截器中处理
      } catch (error) {
        console.error('登录出错:', error)
        // 错误消息已经在响应拦截器中处理
      } finally {
        loading.value = false
      }
    } else {
      console.log('表单验证失败')
    }
  })
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}

// 组件挂载时清理不再需要的localStorage键
onMounted(() => {
  // 移除旧的记住账号选项键，因为我们现在总是记住账号
  localStorage.removeItem('rememberUser')
  localStorage.removeItem('rememberMerchant')
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url('@/assets/images/login-background.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(5px);
}

.login-title {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30px;
  color: #409EFF;
}

.login-tabs {
  margin-bottom: 20px;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
}

.login-options {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  font-size: 14px;
}

.register-link {
  color: #409EFF;
  cursor: pointer;
}

.register-link:hover {
  text-decoration: underline;
}
</style>
